package converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import dao.ClienteDAO;
import model.Cliente;

@FacesConverter(value = "ClienteConverter", forClass = Cliente.class)
public class ClienteConverter implements Converter {
	private ClienteDAO dao = new ClienteDAO();
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		System.out.println("Passando ClienteConverter getAsObject value ->"+ value + " " + component.getAttributes().get(value));
	    if (value != null && !value.isEmpty()) {
            return dao.searchById(value);
        }
        return null;
    }

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value instanceof Cliente) {
			Cliente cliente = (Cliente) value;
            if (cliente != null && cliente instanceof Cliente && cliente.getId() != null) {
                component.getAttributes().put( cliente.getId().toString(), cliente);
                return cliente.getId().toString();
            }
        }
        return "";
	}

}
